<?php

namespace backend\modules\admin\models\searchs;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\modules\admin\models\Menu as MenuModel;

/**
 * Menu represents the model behind the search form about [[\backend\modules\admin\models\Menu]].
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class Menu extends MenuModel
{
    public $client_id = 2;
    public $search;
    public $limit;

    public function init()
    {
        if (!Yii::$app->request->isPost) {
            $this->load(Yii::$app->session->get('mod_admin.menu.items'));
        }
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'parent', 'ordering', 'client_id', 'limit'], 'integer'],
            [['name', 'route', 'parent_name', 'search'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Searching menu
     * @param array $params
     * @return \yii\data\ActiveDataProvider
     */
    public function search($params)
    {
        $query = MenuModel::find()
            ->alias('t')
            ->joinWith('menuParent p')
            ->joinWith('menuTypes m');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'lft' => SORT_ASC
                ]
            ]
        ]);

        $sort = $dataProvider->getSort();
        $sort->attributes['menuParent.name'] = [
            'asc' => ['p.name' => SORT_ASC],
            'desc' => ['p.name' => SORT_DESC]
        ];
        $sort->attributes['menuTypes.title'] = [
            'asc' => ['m.title' => SORT_ASC],
            'desc' => ['m.title' => SORT_DESC]
        ];

        $this->load($params);
        if (Yii::$app->request->isPost) {
            unset($params[Yii::$app->request->csrfParam]);
            Yii::$app->session->set('mod_admin.menu.items', $params);
        }

        if (!$this->validate()) {
            return $dataProvider;
        }

        if ($this->limit) {
            $dataProvider->pagination->pageSize = $this->limit;
        } else {
            $this->limit = $dataProvider->pagination->pageSize;
        }

        $query->andFilterWhere([
            't.parent' => $this->parent,
            'm.client_id' => $this->client_id
        ]);

        $query->andFilterWhere(['like', 'lower(t.name)', strtolower($this->name)])
            ->andFilterWhere(['like', 't.route', $this->route])
            ->andFilterWhere(['like', 'lower(parent.name)', strtolower($this->parent_name)]);

        return $dataProvider;
    }

}
